package com.autonavi.collapse.task.context.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author : longwanheng
 * create at:  2020/10/16  5:31 下午
 * @description: 网络工具类
 */
public class NetUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(NetUtils.class);

    private static final String localIp;

    static {
        localIp = fatchLocalIp();
    }

    public static String getLocalIp(){
        return localIp;
    }

    private static String fatchLocalIp() {
        String localIp = null;//getLocalIp("titan.amap.com");
        if (localIp != null) {
            return localIp;
        }
        List<String> ips = null;
        try {
            ips = getAllLocalIp();
        }catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        if (ips != null && !ips.isEmpty()) {
            return ips.get(0);
        }
        return null;
    }

    private static String getLocalIp(String remoteAddress) {
        if (remoteAddress == null) {
            return null;
        }
        String ip;
        int port = 80;
        String[] split = remoteAddress.split(":");
        if (split.length > 1) {
            ip = split[0];
            try {
                port = Integer.parseInt(split[1]);
            }catch (NumberFormatException e) {
                LOGGER.error(remoteAddress + " is not a vaild address");
                return null;
            }
        }else {
            ip = remoteAddress;
        }
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port));
            InetAddress localAddress = socket.getLocalAddress();
            if (localAddress != null) {
                return localAddress.getHostAddress();
            }
        }catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }finally {
            if (socket != null){
                try {
                    socket.close();
                }catch (IOException e){

                }
            }
        }
        return null;
    }

    private static List<String> getAllLocalIp() throws Exception{
        List<String> result = new ArrayList<>();
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface ni = networkInterfaces.nextElement();
            Enumeration<InetAddress> ias = ni.getInetAddresses();
            while (ias.hasMoreElements()) {
                InetAddress ip = ias.nextElement();
                if (!ip.isLoopbackAddress() && (ip instanceof Inet4Address)) {
                    result.add(ip.getHostAddress());
                }
            }
        }
        return result;
    }

}
